//
//  BLFontWithColor.swift
//  BLLiveTelecast
//
//  Created by BigL055 on 16/5/25.
//  Copyright © 2016年 bigL.liveTelecast.com. All rights reserved.
//


import Foundation
import FMDB


class BLGDBTool: NSObject {
    
    // 单例
    static let shareInstance: BLGDBTool = BLGDBTool()
    
    var dbQueue: FMDatabaseQueue!
    
    
    override init() {
        super.init()
        
        // 创建数据库路径
        let basePath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first
        let fullPath = basePath! + "/BLLiveTelecast.sqlite"
        print(fullPath)
        
        // 根据路径 创建一个数据库对象
        dbQueue = FMDatabaseQueue(path: fullPath)
    }
    
    func createTable(tableName : String) {
        
        let sql = "CREATE TABLE IF NOT EXISTS BlackList(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, nickName TEXT, uid REAL)"
        
        dbQueue.inDatabase { (db: FMDatabase!) -> Void in
            if db.executeUpdate(sql, withArgumentsInArray: nil)
            {
                print("创建表成功")
            }else
            {
                print("创建表失败")
            }
        }

    }
    
    
    func insertRecords() {
        
        let sql = "insert into t_student(name, score) values('sz', 100)"
        dbQueue.inTransaction { (db: FMDatabase!, stop) -> Void in
            
            for _ in 0...9999
            {
                db.executeUpdate(sql, withArgumentsInArray: nil)
            }
            
            stop.memory = true
        }
        
    }
    
    
    func insert() {
        
        let sql = "insert into t_student(name, score) values('sz', 100)"
        
        
        dbQueue.inDatabase { (db: FMDatabase!) -> Void in
            if db.executeUpdate(sql, withArgumentsInArray: nil)
            {
                print("插入成功")
            }else
            {
                print("插入失败")
            }
        }
        
        
    }
    
    func query() {
        
        let sql = "select name, score from t_student"
        
        
        dbQueue.inDatabase { (db: FMDatabase!) -> Void in
            
            let resultSet = db.executeQuery(sql, withArgumentsInArray: nil)
            while resultSet.next()
            {
                
                let name = resultSet.stringForColumn("name")
                let score = resultSet.doubleForColumn("score")
                print(name, score)
                
            }
        }
        
        
    }
}
